package com.example.demofdfs.util;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import net.neoremind.sshxcute.core.Result;

/**
 * shellCommand连接池
 * @author 
 *
 */
public abstract class CommandPool {

	private static Queue<Command> pool = new ConcurrentLinkedQueue<>();
	private static int size = 0;
	private static int max = 20;
	private static ThreadLocal<Command> threadLocal = new ThreadLocal<>();
	
	private static Command getCommand() {
//		if (pool == null)
//			init();
		
		Command c = null;
		
		if (! pool.isEmpty())
			c = pool.poll();
		else {
			if (size < max)
				c = createCommand();
			else {
				int i = 30;
				while ((c = pool.poll()) == null)
				{
					try {
						Thread.sleep(3);
						i -= 3;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if (i < 0) {
						throw new RuntimeException("获取连接超时!");
					}
				}
			}
		}
		
		threadLocal.set(c);
		return c;
	}
	
	private static Command createCommand() {
		Command c = null;
		if (size < max) {
			c = new ShellCommand();
			pool.offer(c);
			size++;
		}
		return c;
	}
	
	public static Result exec(String cmd) {
		Result r;
		Command c = getCommand();
		try {
			r = c.exec(cmd);
		} finally {
			disCommane();
		}
		return r;
	}
	
	private static void disCommane() {
		
		Command c = threadLocal.get();
		if (pool.size() < max) {
			pool.offer(c);
		}
		threadLocal.remove();
	}
	
//	private static void init() {
//		pool = new LinkedList<>();
//		for (int i = 0; i < 20; i++) {
//			Command c = new ShellCommand();
//			pool.offer(c);
////			new Thread(()-> c.initConnection()).start();
//		}
//	}
}
